<?php
/*
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

/**
 * \file
 */
/// signifies an error with the submitted option
define("NAMEERR", 1);
/// signifies an error with the submitted request
define("REQUESTERR", 1 << 1);
require_once(".ht-inc/ec2.php");
//require_once(".ht-inc/vcl.php");

////////////////////////////////////////////////////////////////////////////////
///
/// \fn displayOptions()
///
/// \brief prints the brokering options on the page "broker.php"
///
////////////////////////////////////////////////////////////////////////////////
function displayOptions() {
        $update = getContinuationVar('update', 0);

        global $value;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Brokering Options</h2>\n";
                $rt .= "<p>Please select one of the options below to continue</p>";
                $rt .= "<div id=\"style\">\n";
        }
        $_SESSION['usersessiondata'] = array();

        $options = array();
        $options = getOptions();
#       print "In broker";
        if(empty($options)) {
                print "No options to be displayed<br>\n";
                return;
        }
        $rt .= "<TABLE>";
        foreach($options as $value){
               $rt .= "   <TR>";
                $rt .= "    <TD align=center>\n";
		$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
                if($value == "Acquire Resources")
                {
			$cont = addContinuationsEntry('acquireResources');
			$rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
			$rt .= "<INPUT type=submit title=\"Acquire resources from different providers\" value=\"$value\">\n";

//			$rt .= "<button onclick=\"window.location.href='index.php?mode=acquireResources'\">$value</button>\n";
                        //$rt .= "onClick=\"showCloudProviders()\"/>\n";
                        $mode = "acquireResources";
                }
                if($value == "Release Resources")
                {
			$cont = addContinuationsEntry('releaseResources');
                        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
			$rt .= "<INPUT type=submit title=\"Release the acquired resources\" value=\"$value\">\n";
//                        $rt .= "<button onclick=\"window.location.href='index.php?mode=releaseResources'\">$value</button>\n";
                        //$rt .= "onClick=\"showCloudProviders()\"/>\n";
                        $mode = "releaseResources";
                }
		if($value == "View Brokered Resources")
		{
			$cont = addContinuationsEntry('viewResources');
                        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
                        $rt .= "<INPUT type=submit title=\"View list of acquired resources\" value=\"$value\">\n";
			$mode = "viewResources";
		}
                if($value == "Statistics")
                {
			$cont = addContinuationsEntry('statistics');
                        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
			$rt .= "<INPUT type=submit title=\"View Statistics for acquired resources\" value=\"$value\">\n";

//                        $rt .= "<button onclick=\"window.location.href='index.php?mode=showStatistics'\">$value</button>\n";
                        //$rt .= "onClick=\"displayStatistics()\"/>\n";
                        $mode = "statistics";
                }
		$rt .= "</FORM>\n";
                $rt .= "    </TD>\n";
                $rt .= "   </TR>";
        }
        $rt .= "</table>";

#       print $rt;
/*              $rt .= "<TR>\n";
                $rt .= "<TD>\n";
                $rt .= "<button dojoType=\"dijit.form.Button\" type=\"button\">\n";
                $rt .= "   $value\n";
                $rt .= "<script type=\"dojo/method\" event=\"onClick\">\n";
                if($value == "Acquire Resources")
                {
                        $rt .= "    showCloudProviders();\n";
                        $cont = addContinuationsEntry('showCloudProviders', array('update' => 1));
                }
                elseif($value == "Release Resources")
                {
                        $rt .= "    showCloudProviders();\n";
                        $cont = addContinuationsEntry('showCloudProviders', array('update' => 1));
                }
                elseif($value == "Statistics")
                {
                        $rt .= "    showstatistics();\n";
                        $cont = addContinuationsEntry('showStatistics', array('update' => 1));
                }

                $rt .= "  </script>\n";
                $rt .= "   </button><br>\n";
                $rt .= "</TD>\n";
                $rt .= "</TR>\n";
        }
        $rt .= "</TABLE>\n";
*/
	$rt .= "<br><br>\n";
	$rt .= "<TABLE>\n";
        $rt .= "<form name=keys>\n";
        $cont = addContinuationsEntry('addkeys');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "<TR><TD><label for=ec>To manage authentication details for Amazon EC2: </label></TD><TD><a href=\"" . BASEURL .SCRIPT . "?continuation=$cont\">Click here</a></TD></TR>\n";
        $rt .= "</form>";
        $rt .= "</TABLE>\n";
	
	$rt .= "<TABLE>\n";
        $rt .= "<form name=ips>\n";
        $cont = addContinuationsEntry('addips');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "<TR><TD><label for=vcl>To manage remote VCL Cloud IP Address: </label></TD><TD><a href=\"" . BASEURL .SCRIPT . "?continuation=$cont\">Click here</a></TD></TR>\n";
        $rt .= "</form>";
        $rt .= "</TABLE>\n";
        $rt .="</div>";

        $_SESSION['usersessiondata'] = array();
        print $rt;

/*
	print "Get XMLData";	
	$params = array('Action' => 'DescribeImages');
        getXMLData($params, 'ec2.amazonaws.com');
	print "After creating XML file...Before parsing\n";
	parseXMLFile();
	print "After parsing\n";
*/	
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn showCloudProviders()
///
/// \brief displays the list of cloud providers available
///
////////////////////////////////////////////////////////////////////////////////
function showCloudProviders()
{
        global $data, $name, $mode, $count, $prov1;
        $update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Acquire Resources</h2>\n";
                $rt .= "<div id=\"brokerresoptions\">\n";
        }
        $providers = array();
        $providers = getBrokers();

        if(empty($providers)) {
                print "No options to be displayed<br>\n";
                return;
        }

        $rt .= "<TABLE>";
        $rt .= "<TR><TD>\n";
        $rt .= "<label for=cp>Cloud Providers: </label>\n";
        $rt .= "</TD>\n";

	$rt .= "<TD>\n";
	$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
	print $rt;
	printSelectInput("prov", $providers, $prov1);
	$cont = addContinuationsEntry('getResource');
	$rt = '';
	$rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "</TD><TD><input type=submit value=\"Get list of resources\"/></TD></TR>\n";
	$rt .= "</form>";
	$rt .= "</TABLE>\n";
	
/*	$rt .= "<TABLE>\n";
	$rt .= "<form name=keys>\n";
	$cont = addContinuationsEntry('addkeys');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
	$rt .= "<TR><TD><label for=ec>To Add keys<TD><a href=\"" . BASEURL .SCRIPT . "?continuation=$cont\">Add keys</a></TD></TR>\n";
	$rt .= "</form>";
        $rt .= "</TABLE>\n";
        $rt .= "</div>";
*/
        print $rt;
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn addIPs()
///
/// \brief Add the remote VCL cloud IP address
///
////////////////////////////////////////////////////////////////////////////////
function addIPs()
{
	global $data, $name, $mode, $count, $prov1, $provsel, $res1;
        $update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Add IP Address of remote VCL Cloud</h2>\n";
                $rt .= "<div id=\"addip\">\n";
        }
/*      $providers = getBrokers();
        $rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $rt .= "<TABLE>\n";
        $rt .= "<TR><TD><label for=pro> Cloud provider: </label></TD><TD>\n";
*/
        print $rt;

        $cont = addContinuationsEntry('ipsadded');
        $rt = '';
	$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $rt .= "<TABLE>\n";
        $rt .= "</TD></TR><INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "<TR><TD><label for=pub>IP address of remote VCL: </label></TD><TD><input type=text name=remVCL></TD></TR>\n";
        $rt .= "<TR><TD><label for=pri>IP address of local VCL:  </label></TD><TD><input type=text name=locVCL></TD></TR>\n";
        $rt .= "<TR><TD><input type=submit value=\"Store IP Address\"></TD>\n";
        $rt .= "</form>\n";
        $rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $cont = addContinuationsEntry('brokerResources');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "<TD><input type=submit value=\"Cancel\"></TD></TR>\n";
        $rt .= "</form>\n";
        $rt .= "</TABLE>\n";

	$query = "SELECT * FROM ipaddress";
	$execq = doQuery($query, 101);	
	$row = mysql_fetch_row($execq);

	$rt .= "<br><br>\n";
	$rt .= "<h2>IP Addresses stored in the database</h2>\n";

	$query = "SELECT * FROM ipaddress";
        $execq = doQuery($query, 101);
	
	if(!empty($row))
	{
	$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $cont = addContinuationsEntry('deleteIPs');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
	$rt .= "<TABLE border=2>\n";
        $rt .= "<TR><TH>Delete?</TH><TH>Local Cloud IP</TH><TH>Remote Cloud IP</TH></TR>\n";
	while($row = mysql_fetch_assoc($execq))
        {
		$localip = $row['localip'];
		$remoteip = $row['cloudip'];
		$rt .= "<TR><TD><input type=\"checkbox\" name=\"removeIP[]\" value=\"" . $remoteip . "\"/></TD>\n";
	        $rt .= "<TD>$localip</TD>\n";
                $rt .= "<TD>$remoteip</TD></TR>\n";
        }
        $rt .= "</TABLE>\n";
	$rt .= "<br><input type=submit value=\"Delete\">\n";	
	$rt .= "</form>\n";
	}
	else
	{
		print "<p>No entries for remote VCL Cloud</p>\n";
	}
        $rt .= "</div>";
        print $rt;	
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn deleteIPs()
///
/// \brief Deleted the entries corresponding to remote VCL cloud
///
////////////////////////////////////////////////////////////////////////////////
function deleteIPs()
{
	$selRes = $_POST['removeIP'];
        $update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Delete IP addresses</h2>\n";
                $rt .= "<div id=\"delip\">\n";
        }
	if(empty($selRes))
	{
		print "<p>No fields selected</p>\n";
	}
	else
	{
		print "<h2>Delete Confirmation</h2>\n";
	        $numofRes = count($selRes);
        	for($i=0; $i < $numofRes; $i++)
	        {
        		$query = "DELETE FROM ipaddress where cloudip= '$selRes[$i]'";
			doQuery($query, 105);
	                print "<p>Deleted the remote VCL IP address: $selRes[$i]</p><br>";
		}
	}
	$rt = '';
	$rt .= "<TABLE><TR><TD><form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
	$cont = addContinuationsEntry('brokerResources');
	$rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
	$rt .= "<input type=submit value=\"Back\">\n";
	$rt .= "</form></TD></TR>\n";
	$rt .= "</TABLE>\n";
	print $rt;	
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn addKeys()
///
/// \brief Add the public and private keys specific to a provider
///
////////////////////////////////////////////////////////////////////////////////
function addKeys()
{
	global $data, $name, $mode, $count, $prov1, $provsel, $res1;
	$update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Add Key Pairs</h2>\n";
                $rt .= "<div id=\"akeys\">\n";
        }
/*	$providers = getBrokers();
	$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";	
	$rt .= "<TABLE>\n";
	$rt .= "<TR><TD><label for=pro> Cloud provider: </label></TD><TD>\n";
*/
	//print $rt;
		
//	printSelectInput("prov", $providers, $prov1);
	$cont = addContinuationsEntry('keysadded');
        //$rt = '';
	$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" name=adKeys method=post>\n";
	$rt .= "<TABLE>\n";
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";	
	$rt .= "<TR><TD><label for=pub>Public Key: </label></TD><TD><input type=text name=pubk></TD></TR>\n";
	$rt .= "<TR><TD><label for=pri>Private Key: </label></TD><TD><input type=text name=prik></TD></TR>\n";
	$rt .= "<TR><TD><input type=submit value=\"Store keys\"></TD>\n";
	$rt .= "</form>\n";
	$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
	$cont = addContinuationsEntry('brokerResources');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
	$rt .= "<TD><input type=submit value=\"Cancel\"></TD></TR>\n";
        $rt .= "</form>\n";
	$rt .= "</TABLE>\n";

	$query = "SELECT pub_key, pri_key FROM provkeys where provider='ec2'";
        $execq = doQuery($query, 101);
	$row = mysql_fetch_row($execq);

        $rt .= "<br><br>\n";
        $rt .= "<h2>Key pairs stored in the database</h2>\n";

        $query = "SELECT pub_key, pri_key FROM provkeys where provider='ec2'";
        $execq = doQuery($query, 101);

	if(!empty($row))
	{
	$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $cont = addContinuationsEntry('deleteKeys');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";        
	$rt .= "<TABLE border=2>\n";
        $rt .= "<TR><TH>Delete?</TH><TH>Public Key</TH><TH>Private Key</TH><TH>Provider</TH></TR>\n";
        while($row = mysql_fetch_assoc($execq))
        {
		$pubkey = $row['pub_key'];
		$rt .= "<TR><TD><input type=\"checkbox\" name=\"removeKey[]\" value=\"" . $pubkey . "\"/></TD>\n";
                $rt .= "<TD>$pubkey</TD>\n";
                $prikey = $row['pri_key'];
                $rt .= "<TD>$prikey</TD>\n";
		$rt .= "<TD>Amazon EC2</TD></TR>\n";
        }
        $rt .= "</TABLE>\n";
	$rt .= "<br><input type=submit value=\"Delete keys\">\n";
	$rt .= "</form>\n";
	}
	else
	{
		$rt .= "<p>No keys present for this provider</p>\n";
	}
	$rt .= "</div>";
	print $rt;
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn deleteKeys()
///
/// \brief Deletes the Keypairs from the  database
///
////////////////////////////////////////////////////////////////////////////////
function deleteKeys()
{
        $selRes = $_POST['removeKey'];
	$update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Delete Keys</h2>\n";
                $rt .= "<div id=\"delk\">\n";
        }
	if(empty($selRes))
	{
        	print "<p>No Keys selected</p>\n";
        }
        else
        {
	        print "<h2>Delete Confirmation</h2>\n";
        	$numofRes = count($selRes);
                for($i=0; $i < $numofRes; $i++)
                {
                	$query = "DELETE FROM provkeys where pub_key='$selRes[$i]'";
			doQuery($query, 105);
                        print "<p>Deleted the Key pair successfully</p>";
                }
	}
        $rt = '';
        $rt .= "<TABLE><TR><TD><form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $cont = addContinuationsEntry('brokerResources');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "<input type=submit value=\"Back\">\n";
        $rt .= "</form></TD></TR>\n";
        $rt .= "</TABLE>\n";
	$rt .= "</div>";
        print $rt;	
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn storeIPs()
///
/// \brief Stores the remote VCL IP in the database
///
////////////////////////////////////////////////////////////////////////////////
function storeIPs()
{
        global $data, $name, $mode, $count, $prov1, $provsel, $res1;
        $update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Add IP Address</h2>\n";
                $rt .= "<div id=\"aips\">\n";
        }
        print $rt;

        $remoteip = $_POST['remVCL'];
        $localip = $_POST['locVCL'];

	if(!empty($remoteip) || !empty($localip))
	{
	        $query = "INSERT INTO ipaddress (`localip`, `cloudip`) VALUES ('$localip', '$remoteip')";
	        doQuery($query, 305);
        	print "<p>IP address added to database</p>\n";
		print "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        	$cont = addContinuationsEntry('brokerResources');
	        print "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        	print "<input type=submit value=\"Back\">\n";
	        print "</form>\n";
	}
	else
	{
		print "<p><font color=red size=4>IP Address cannot be NULL</font></p>\n";
		print "<p>IP Addresses not added to the database</p>";
		print "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        	$cont = addContinuationsEntry('addips');
	        print "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        	print "<input type=submit value=\"Back\">\n";
	        print "</form>\n";
	}
        print "</div>";
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn storeKeys()
///
/// \brief Stores the public and private keys in the database
///
////////////////////////////////////////////////////////////////////////////////
function storeKeys()
{
        $update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Add Keys</h2>\n";
                $rt .= "<div id=\"akeys\">\n";
        }
	print $rt;
	//$provider = $_POST['prov'];
	$pubk = $_POST['pubk'];
	$prik = $_POST['prik'];

	if(empty($pubk) || empty($prik))
	{
		print "<p><font color=red size=3>Keys cannot be NULL</font></p>\n";
		print "<p>Couldn't add the keys</p>\n";
		print "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        	$cont = addContinuationsEntry('addkeys');
	        print "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        	print "<input type=submit value=\"Back\">\n";
	        print "</form>\n";
	}
	else
	{
		$query = "INSERT INTO provkeys (`id`, `provider`, `pub_key`, `pri_key`) VALUES (NULL, 'ec2', '$pubk', '$prik')";
		doQuery($query, 305);
		print "<p>Keys added to database</p>";
		print "<br>\n";
		print "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
                $cont = addContinuationsEntry('brokerResources');
                print "<INPUT type=hidden name=continuation value=\"$cont\">\n";
                print "<input type=submit value=\"Back\">\n";
                print "</form>\n";
	}
	print "</div>";
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn showResources()
///
/// \brief Shows the list of resources associated with a cloud provider
///
////////////////////////////////////////////////////////////////////////////////
function showResources()
{
        global $data, $name, $mode, $count, $prov1, $provsel, $res1, $params;
        $update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Acquire Resources</h2>\n";
                $rt .= "<div id=\"acquires\">\n";
        }
        $providers = array();
        $providers = getBrokers();

        if(empty($providers)) {
                print "No cloud providers<br>\n";
                return;
        }

	$rt .= "<TABLE>\n";
	$rt .= "<TR><TD>\n";
	$rt .= "<label for=cp>Cloud Provider: </label>\n";
	$rt .= "</TD><TD>\n";
//        $rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";

//        printSelectInput("prov", $providers, $prov1);
//        $cont = addContinuationsEntry('getResource');
        $provret = processInputVar("prov", ARG_NUMERIC);
        if($provret == 0)
                $provsel = "VCL";
        elseif($provret == 1)
                $provsel = "Amazon EC2";
	$rt .= "<INPUT type=text size=15 value=\"$provsel\" disabled/></TD>\n";
	$rt .= "<form action= \"" . BASEURL . SCRIPT . "\" method=post>\n";	
	$cont = addContinuationsEntry('acquireResources');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "</TD><TD><input type=submit value=\"Reselect provider\"/></TD></TR>\n";
	$rt .= "</form>\n";

        $rt .= "</TABLE>\n";
	print $rt;
	$rt = '';
	
	if($provsel == "Amazon EC2")
	{
		$params = array('Action' => 'DescribeImages');
		getXMLData($params, 'ec2.amazonaws.com');
		parseXMLFile();
	}

	global $query, $img1, $images;	
	$id = 0;
        $res = array();
        if($provsel == "Amazon EC2")
        {
                $query = "SELECT * FROM ec2ImageList where provider=\"" . $provsel . "\" order by ami_name";
		$execq = doQuery($query, 101);
        }
        if($provsel == "VCL")
        {
		$images = remoteVCLCall('XMLRPCgetImages', array());	
        }
		
	$rt .= "<form action= \"" . BASEURL . SCRIPT . "\" method=post>\n";
	$cont = addContinuationsEntry('acquired');
	$rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";

	$rt .= "<INPUT type=hidden name=provider value=\"$provsel\">\n";	

	$rt .= "<TABLE>";
        $rt .= "<TR><TD>\n";
        $rt .= "<label for=lofres>List of Resources: </label></TD>\n";

        $rt .= "<TD>\n";
	print $rt;
	$rt = '';
	
	if($provsel == "Amazon EC2")
	{
		if(empty($execq))
		{
			print "No resources offered by this provider\n";
			break;
		}
		$rt .= "<TD><select name=res>";
	        while($row = mysql_fetch_assoc($execq))
	        {
			$rt .= "<option value=\"" . $row['ami_id'] . "\">" . $row['ami_name'] . " ( " . $row['ami_id'] . " )</option>\n";
			//print $row['id'];
        	}
	
		$rt .= "</select>\n";
        }
	elseif($provsel == "VCL")
	{
		$rt .= "<TD><select name=res>";
                foreach($images as $img)
                {
                        $rt .= "<option value=\"" . $img['name'] . "\">" . $img['name'] . " </option>\n";
                        //print $row['id'];
                }

                $rt .= "</select>\n";
	}
	$rt .= "</TD></TR>\n";
        $rt .= "</TABLE>\n";

        $rt .= "<br><br>\n";
	$rt .= "<TABLE>\n";
        $rt .= "<TR>\n";
        $rt .= "<TD><label for=noinstance>Number of instances:</label></TD>\n";
        $rt .= " <TD>\n";
        $rt .= " <INPUT type=text name=noinstance maxlength=10 ";
        $rt .= "size=15></TD></TR>\n";

/*        $rt .= "<TR>\n";
        $rt .= " <TD><label for=restime>Time of reservation:</label></TD>\n";
        $rt .= " <TD><INPUT type=text name=restime maxlength=10 ";
        $rt .= "size=15></TD>\n";
*/
	$rt .= "<TR><TD><INPUT id=ressubmit type=submit value=\"Reserve\" onclick=selectEnvironment();>";
	$rt .= "</TD>\n";
	$rt .= "</form>\n";
	$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $cont = addContinuationsEntry('brokerResources');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "<TD><input type=submit value=\"Back\"/></TD></TR>\n";
        $rt .= "</TABLE></form>"; 
	print $rt;
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn release()
///
/// \brief Releases the borrowed resources and removes those entries from database
///
////////////////////////////////////////////////////////////////////////////////
function release()
{
        $update = getContinuationVar('update', 0);
        $id = 0;
        $rt = '';
        if(! $update) {
                $rt .= "<h2>Release Resources</h2>\n";
                $rt .= "<div id=\"releaseres\">\n";
        }
        global $instanceid, $imagename, $ami_id;
        $provider = "Amazon EC2";	// Get the list of Cloud Providers
        $rt = '';

        if($provider  == "Amazon EC2")
        {
                $rt .= "<h2>Resources borrowed from Amazon EC2</h2>";
                $query = "SELECT instanceid, ami_id from ec2BrokeredInstances";
                $execq = doQuery($query, 101);
		$row = mysql_fetch_row($execq);
		
		if(!empty($row))
		{
			$rt .= "<TABLE border=2>\n";
	                $rt .= "<TR><TH>Select?</TH><TH>Instance ID</TH><TH>AMI ID</TH><TH>Image Name</TH><TH>Provider</TH></TR>\n";
			$rt .= "<form action=\"" . BASEURL . SCRIPT . "\" method=post>";
	                $cont = addContinuationsEntry('removeResources');
        	        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
			
			$query = "SELECT instanceid, ami_id from ec2BrokeredInstances";
	                $execq = doQuery($query, 101);
                	while($row = mysql_fetch_assoc($execq))
	                {
        	                $instanceid = $row['instanceid'];
				$rt .= "<TR><TD><input type=\"checkbox\" name=\"toRelease[]\" value=\"" . $instanceid . "\"/></TD>\n";
                        	$rt .= "<TD>$instanceid</TD>\n";
	                        $ami_id = $row['ami_id'];
        	                $rt .= "<TD>$ami_id</TD>\n";
                	        $rt .= "<INPUT type=hidden name=amiid value=\"$ami_id\">\n";
				$query1 = "SELECT ami_name from ec2ImageList where ami_id='$ami_id'";
        	                $res = doQuery($query1, 101);
                	        while($row1 = mysql_fetch_assoc($res))
                        	{
					$imagename = $row1['ami_name'];
        	                        $rt .= "<TD>$imagename</TD>\n";
                	                $rt .= "<TD>Amazon EC2</TD>\n";
                        	}
	                        $rt .= "</TR>\n";
        	        }
                	$rt .= "</TABLE>\n";
			$rt .= "<br><input type=submit value=\"Release\"/>";
			$rt .= "<input type=hidden name=\"provider\" value=\"Amazon EC2\">\n";
			$rt .= "</form>\n";
		}
		else
		{
			$rt .= "<p>No resources borrowed from this provider</p>\n";
		}
        }
        print $rt;

        $rt = '';
        $provider = "VCL";
        if($provider == "VCL")
        {
	        $query = "SELECT resourceid from vclResources where type=13";
		$execq = doQuery($query, 101);
		$row = mysql_fetch_row($execq);
                $rid = $row[0];
		
		print "<h2>Resources borrowed from VCL</h2>";	
		if(empty($rid))
		{
			print "<p>No resources borrowed from this provider</p>\n";
			return;
		}
		else
		{
			$query2 = "SELECT name from image WHERE id=$rid";
		        $res = doQuery($query2, 101);
			//print $res;
		        if(empty($res))
		        {
		    	    print "<p>No resources borrowed from this provider</p>\n";
		        }
	        	else
	                {
		                $rt .= "<TABLE><TR><TD><form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        		        $cont = addContinuationsEntry('removeResources');
                		$rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
				$rt .= "<input type=hidden name=\"provider\" value=\"VCL\">\n";
		                $rt .= "<input type=submit value=\"Release\">\n";
		                $rt .= "</form></TD></TR>\n";
        		        $rt .= "</TABLE>\n";
				$rt .= "<TABLE border=2>\n";
		                $rt .= "<TR><TH>Resource name</TH><TH>Provider</TH></TR>\n";
		                while($row = mysql_fetch_assoc($res))
		                {
	        	 	       $image = $row['name'];
	                	       $rt .= "<TR><TD>$image</TD>\n";
	        	               $rt .= "<TD>VCL</TD>\n";
	                	       $rt .= "</TR>\n";
                        	}
	                        $rt .= "</TABLE>\n";
        	        }
        	}
	}	
	$rt .= "</div>\n";
        print $rt;
}
	
////////////////////////////////////////////////////////////////////////////////
///
/// \fn removeResources()
///
/// \brief Releases the resources selected to be released
///
////////////////////////////////////////////////////////////////////////////////
function removeResources()
{
	$provider = $_POST['provider'];
	//print $provider;
	
	if($provider == "VCL")
	{
		print "<h2>Release Confirmation</h2>\n";
		releaseBrokerResources();	
		$rt = '';
		$rt .= "<TABLE><TR><TD><form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        	$cont = addContinuationsEntry('brokerResources');
	        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        	$rt .= "<input type=submit value=\"Back\">\n";
	        $rt .= "</form></TD></TR>\n";
        	$rt .= "</TABLE>\n";
		print $rt;
	}

	if($provider == "Amazon EC2")
	{
		$selRes = $_POST['toRelease'];
		$amiid = $_POST['amiid'];
		if(empty($selRes))
		{
			print "<p>No Resources selected</p>\n";
		}
		else
		{
			print "<h2>Release Confirmation</h2>\n";
			$numofRes = count($selRes);
			for($i=0; $i < $numofRes; $i++)
			{
				releaseEC2BrokerResources($selRes[$i], $amiid);
				//print "$selRes[$i]<br>";
				//print "    $amiid<br>";
			}
			print "<p>Released $numofres instances successfully!</p>\n";
		}
		$rt = '';
                $rt .= "<TABLE><TR><TD><form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
                $cont = addContinuationsEntry('brokerResources');
                $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
                $rt .= "<input type=submit value=\"Back\">\n";
                $rt .= "</form></TD></TR>\n";
                $rt .= "</TABLE>\n";
                print $rt;
	}
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn reserve()
///
/// \brief Reserves the specified number of resources from the specific cloud provider
///
////////////////////////////////////////////////////////////////////////////////
function reserve()
{
	$provider = $_POST['provider'];
	//$time = $_POST['restime'];
	$selinst = $_POST['res'];
	$numofins = $_POST['noinstance'];	

	if($provider == "Amazon EC2")
	{
		$params = array('Action' => 'RunInstances');
		createInstance($params, 'ec2.amazonaws.com', $selinst, $numofins);
	}
	elseif($provider == "VCL")
	{
		print "<h2>Acquire Confirmation</h2>\n";
		$check = verifyUserRequest($numofins);

		if($check > 0)
		{
			$images = remoteVCLCall('XMLRPCgetImages', array());
			foreach ($images as $image) {
				if ($selinst === $image['name']) {
					//print "<p>Valid image type</p>";
					$imgid = addNonLocalImage($image);
					//print $imgid;
					$ret = 1;
				}
			}
				
			for ($i = 1; $i <=$check; $i++) {
				$compid = addNonLocalComputer($i);
	                        //print $compid;
			}
		}
		print "<p>Requested resources successfully reserved</p>";
		print "<p>Reserved $numofins instance of $selinst</p>";
	}
	$rt = '';
        $rt .= "<TABLE><TR><TD><form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $cont = addContinuationsEntry('brokerResources');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "<input type=submit value=\"Back\">\n";
        $rt .= "</form></TD></TR>\n";
        $rt .= "</TABLE>\n";
        print $rt;
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn viewBrokeredResources()
///
/// \brief displays the list of resources borrowed from different cloud providers
///
////////////////////////////////////////////////////////////////////////////////
function viewBrokeredResources()
{
	global $instanceid, $imagename, $ami_id;
	$provider = "Amazon EC2"; //get list of cloud providers
	$rt = '';
	
	if($provider  == "Amazon EC2")
	{
		$rt .= "<h2>Resources borrowed from Amazon EC2</h2>";
		$query = "SELECT instanceid, ami_id from ec2BrokeredInstances";
		$execq = doQuery($query, 101);
		$row = mysql_fetch_row($execq);

		if(!empty($row))
		{
			$rt .= "<TABLE border=2>\n";
			$rt .= "<TR><TH>Instance ID</TH><TH>AMI ID</TH><TH>Image name</TH><TH>Provider</TH></TR>\n";
			$query = "SELECT instanceid, ami_id FROM ec2BrokeredInstances";
			$execq = doQuery($query, 101);
		
			while($row = mysql_fetch_assoc($execq))
		        {
        		        $instanceid = $row['instanceid'];
				$rt .= "<TR><TD>$instanceid</TD>\n";
	                	$ami_id = $row['ami_id'];
				$rt .= "<TD>$ami_id</TD>\n";
				$query1 = "SELECT ami_name from ec2ImageList where ami_id='$ami_id'";
				$res = doQuery($query1, 101);
				while($row1 = mysql_fetch_assoc($res))
				{
					$imagename = $row1['ami_name'];
					$rt .= "<TD>$imagename</TD>\n";
					$rt .= "<TD>Amazon EC2</TD>\n";
				}
				$rt .= "</TR>\n";
			}
			$rt .= "</TABLE>\n";
		}
		else
		{
			$rt .= "<p>No resources borrowed from this provider</p>\n";
		}
	}
	print $rt;

	$rt = '';
	$provider = "VCL";
	if($provider == "VCL")	
	{
		$query = "SELECT resourceid from vclResources where type=13";
                $execq = doQuery($query, 101);
                $row = mysql_fetch_row($execq);
                $rid = $row[0];

                //print "RID is $rid\n";
                print "<h2>Resources borrowed from VCL</h2>";
                if(empty($rid))
                {
                        print "<p>No resources borrowed from this provider</p>\n";
                        return;
                }
                else
                {
                        $query2 = "SELECT name from image WHERE id=$rid";
                        $res = doQuery($query2, 101);
			//print $res;
                        if(empty($res))
                        {
                            print "<p>No resources borrowed from this provider</p>\n";
                        }
                        else
                        {
                                $rt .= "<TABLE border=2>\n";
                                $rt .= "<TR><TH>Resource name</TH><TH>Provider</TH></TR>\n";
                                while($row = mysql_fetch_assoc($res))
                                {
 		                	$image = $row['name'];
	                                $rt .= "<TR><TD>$image</TD>\n";
					$rt .= "<TD>VCL</TD>\n";	
					$rt .= "</TR>\n";
                                }
                                $rt .= "</TABLE>\n";
                        }
                }
        }
	$rt .= "<TABLE><TR><TD><form action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        $cont = addContinuationsEntry('brokerResources');
        $rt .= "<INPUT type=hidden name=continuation value=\"$cont\">\n";
        $rt .= "<input type=submit value=\"Back\">\n";
        $rt .= "</form></TD></TR>\n";
        $rt .= "</TABLE>\n";

        print $rt;
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn showStatistics()
///
/// \brief displays the statistics associated with the borrowed resources
///
////////////////////////////////////////////////////////////////////////////////
function showStatistics()
{
	$rt = '';
	$rt .= "<h2>Statistics for VCL</h2>";
	$rt .= "<div id=stat>\n";

	$query1 = "SELECT * FROM vclResources";
	$res = doQuery($query1, 106);
	$row1 = mysql_fetch_row($res);

	$query = "SELECT * FROM vclinstances";
	$execq = doQuery($query, 105);
	$row = mysql_fetch_row($execq);

	if(empty($row) && empty($row1))
	{
		$rt .= "<p>No resources borrowed from VCL</p>";
	}
	elseif(empty($row) && !empty($row1))
	{	
		$rt .= "<p>No users using borrowed resources</p>\n";
	}
	elseif(!empty($row))
	{
		$query = "SELECT imageid, requestid, username FROM vclinstances";
	        $execq = doQuery($query, 105);
		
		$rt .= "<TABLE border=2>\n";
                $rt .= "<TR><TH>Image Name</TH><TH>Username</TH><TH>Provider</TH></TR>\n";
		while($row = mysql_fetch_assoc($execq))
		{
			$imageid = $row['imageid'];
			$query1 = "SELECT name from image where id=$imageid";
			$execq1 = doQuery($query1, 105);
			$row1 = mysql_fetch_row($execq1);
			$imagename = $row1[0];
                        $rt .= "<TR><TD>$imagename</TD>\n";
			$username = $row['username'];
			$rt .= "<TD>$username</TD>\n";
                        $rt .= "<TD>VCL</TD>\n";
                        $rt .= "</TR>\n";
		}
		$rt .= "</TABLE>\n";
	}

	/* Statistics for Amazon EC2 */

	$rt .= "<h2>Statistics for Amazon EC2</h2>\n";
	$query1 = "SELECT * FROM ec2Resources";
        $res = doQuery($query1, 106);
        $row1 = mysql_fetch_row($res);

        $query = "SELECT * FROM ec2instances";
        $execq = doQuery($query, 105);
        $row = mysql_fetch_row($execq);

        if(empty($row) && empty($row1))
        {
                $rt .= "<p>No resources borrowed from Amazon EC2</p>";
        }
        elseif(empty($row) && !empty($row1))
        {
                $rt .= "<p>No users using borrowed resources</p>\n";
        }
        elseif(!empty($row))
        {
                $query = "SELECT imageid, requestid, username FROM ec2instances";
                $execq = doQuery($query, 105);

                $rt .= "<TABLE border=2>\n";
                $rt .= "<TR><TH>Image Name</TH><TH>Username</TH><TH>Provider</TH></TR>\n";
                while($row = mysql_fetch_assoc($execq))
                {
                        $imageid = $row['imageid'];
                        $query1 = "SELECT name from image where id=$imageid";
                        $execq1 = doQuery($query1, 105);
                        $row1 = mysql_fetch_row($execq1);
                        $imagename = $row1[0];
                        $rt .= "<TR><TD>$imagename</TD>\n";
                        $username = $row['username'];
                        $rt .= "<TD>$username</TD>\n";
                        $rt .= "<TD>VCL</TD>\n";
                        $rt .= "</TR>\n";
                }
                $rt .= "</TABLE>\n";
        }

	$rt .= "</div>\n";
	print $rt;	
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn getBrokers()
///
/// \brief Gets the list of brokers available for borrowing resources
///
////////////////////////////////////////////////////////////////////////////////
function getBrokers()
{
        $id = 0;
        $brok = array();
        $query = "SELECT name FROM brokers";
        $execq = doQuery($query, 101);

        while($row = mysql_fetch_assoc($execq))
        {
                $brok[$id] = $row['name'];
                $id++;
        }
        if(empty($brok))
        {
                print "There are no resource providers";
        }
        return $brok;
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn getOptions()
///
/// \brief Gets the options to be displayed in the "Broker Resources" page
///
////////////////////////////////////////////////////////////////////////////////
function getOptions()
{
        $id = 0;
        $optreturn = array();
        $query = "SELECT name FROM options";
        $qo = doQuery($query, 101);
        while($row = mysql_fetch_assoc($qo))
        {
                $optreturn[$id] = $row['name'];
                $id++;
        }
        return $optreturn;
}

?>

